package com.las.nogu.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.las.bot.common.Constant;
import com.las.bot.dao.CqMsgUrlDao;
import com.las.bot.dao.SeMemberDao;
import com.las.bot.dao.SeRewardDao;
import com.las.utils.HttpUtils;
import com.las.utils.mirai.CmdUtil;
import com.model.CqMsgUrl;
import com.model.SeMember;
import com.model.SeReward;
import com.utils.JsonUtils;
import com.utils.RedisUtils;
import com.utils.ThreadUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/setu")
public class SeTuController {

    private final Log log = LogFactory.getLog(SeTuController.class);

    private String[] rarity = {"E", "D", "C", "B", "A", "S", "SS", "SSS"};

    private String[] rate = {"正常", "1级", "2级", "3级", "4级", "5级", "6级", "7级", "8级"};

    private Double[] rw = {0.0, 0.0, 0.0, 0.0, 0.005, 0.012, 0.025, 0.034};

    private ThreadPoolExecutor executor = ThreadUtil.getPool();

    @Autowired
    private CqMsgUrlDao cqMsgUrlDao;

    @Autowired
    private SeRewardDao seRewardDao;

    @Autowired
    private SeMemberDao seMemberDao;

    @RequestMapping("/cq")
    public String cq(HttpServletRequest request) throws Exception {
        Object obj = RedisUtils.get("test");
        if (ObjectUtil.isNotNull(obj)) {
            return obj.toString();
        }
        return "fail";
    }


    @RequestMapping("/count")
    public String count(String uId) {
        long userId = Long.parseLong(uId);
        //先查询用户是否有免费次数
        Object timeObj = RedisUtils.get(Constant.SETU_FREE_TIME + userId);
        if (ObjectUtil.isNotNull(timeObj)) {
            log.info("次数已超过5次，您的时间还在冷却中~");
            return "-1";
        }
        Object obj = RedisUtils.get(Constant.SETU_FREE_TAG + userId);
        long incr;
        if (ObjectUtil.isNotNull(obj)) {
            int count = Integer.parseInt(obj.toString());
            if (count >= 5) {
                log.info("次数已超过5次，请1小时后再试~");
                return "-1";
            } else {
                incr = count;
            }
        } else {
            //说明第一次
            incr = 0L;
        }
        return (5 - incr) + "";
    }

    @Scope(value = "prototype")
    @RequestMapping("/roll")
    public String roll(String uId) {
        long userId = Long.parseLong(uId);
        List<CqMsgUrl> totalList = cqMsgUrlDao.getIw233AllTotal();
        Long total = cqMsgUrlDao.getIw233Total();
        // 先检查用户是否充了会员
        SeMember member = seMemberDao.findByUserId(userId);
        if (ObjectUtil.isNull(member)) {
            log.info("该功能需要付费0.1美元，有需要可发红包给蠢狼：1091569752（人工充值）");
            return "-1";
        } else {
            Date now = new Date();
            if (now.after(member.getTime())) {
                log.info("您的会员已过期，请联系蠢狼续费~");
                return "-1";
            }
            if (CollectionUtil.isEmpty(totalList) && totalList.size() != 9) {
                log.info("数据不全无法统计");
                return "-1";
            }
        }
        //查询用户是否有免费次数
        Object timeObj = RedisUtils.get(Constant.SETU_FREE_TIME + userId);
        if (ObjectUtil.isNotNull(timeObj)) {
            log.info("次数已超过5次，您的时间还在冷却中~");
            return "-1";
        }
        Object obj = RedisUtils.get(Constant.SETU_FREE_TAG + userId);
        long incr;
        if (ObjectUtil.isNull(obj)) {
            //说明第一次
            incr = RedisUtils.incr(Constant.SETU_FREE_TAG + userId, 1);
        } else {
            int count = Integer.parseInt(obj.toString());
            if (count >= 5) {
                log.info("次数已超过5次，请1小时后再试~");
                return "-1";
            } else {
                incr = RedisUtils.incr(Constant.SETU_FREE_TAG + userId, 1);
                if (incr == 5) {
                    RedisUtils.set(Constant.SETU_FREE_TIME + userId, "-1", 60 * 60);
                    RedisUtils.del(Constant.SETU_FREE_TAG + userId);
                }
            }
        }
        CqMsgUrl myUrl = cqMsgUrlDao.findIw233Rand();
        StringBuilder sb = new StringBuilder();
        if (CollectionUtil.isEmpty(totalList)) {
            log.info("当前数据库暂无数据");
            return "-1";
        }
        SeReward reward = null;
        for (int i = 0; i < totalList.size(); i++) {
            CqMsgUrl cqMsgUrl = totalList.get(i);
            if (myUrl.getGroupId().equals(cqMsgUrl.getGroupId()) && cqMsgUrl.getGroupId().intValue() > 0) {
                reward = new SeReward();
                reward.setImgId(myUrl.getId());
                Long count = cqMsgUrl.getUserId();
                MathContext mathContext = new MathContext(4, RoundingMode.HALF_UP);
                BigDecimal a = new BigDecimal(count);
                BigDecimal b = new BigDecimal(total);
                BigDecimal result = a.divide(b, mathContext);
                reward.setImgProbability(result.doubleValue());
                reward.setCreateTime(new Date());
                reward.setImgReward(rw[i]);
                reward.setRarityData(rarity[i]);
                reward.setSeData(rate[cqMsgUrl.getGroupId().intValue()]);
                reward.setUserId(userId);

                sb.append("恭喜你抽中了一张图，鉴定如下：").append("\n");
                sb.append("鉴定值：").append(rate[cqMsgUrl.getGroupId().intValue()]).append("\n");
                sb.append("稀有度：").append(rarity[i]).append("\n");
                sb.append("\n").append("[注]：鉴定范围1~8级，稀有度从E到SSS，鉴定与稀有度两者无关！");
                sb.append("\n").append("图片查询可以输指令：#我的色图 ");
                sb.append("\n").append("您目前使用次数为：").append(incr).append("(还剩").append(5 - incr).append("次)");
                break;
            }
        }
        if (StrUtil.isBlank(sb.toString())) {
            sb.append("很遗憾，未抽中！");
            sb.append("\n").append("您目前使用次数为：").append(incr).append("(还剩").append(5 - incr).append("次)");
            return "-1";
        } else {
            SeReward finalReward = reward;
            executor.execute(() -> {
                //后续做排行榜，这里需要记录起来
                if (ObjectUtil.isNotNull(finalReward)) {
                    seRewardDao.saveOrUpdate(finalReward);
                }
            });
        }
        log.info(sb.toString());
        if (ObjectUtil.isNull(reward)) {
            return "-1";
        }
        return reward.getRarityData();
    }


}
